<?php if(! defined('HAS_POWER') ) exit('无权访问!');
/**
==============================================================================
 * Class GraceEx GracePHP的异常和错误句柄类
 * @author 肖永标
 * @date 2014-12-03
==============================================================================
 */
class GraceEx {

    /** GracePHP异常处理handler
     * @param Exception $e 接受的异常类
     */
    public static function exceptionHandler(Exception $e)
    {
        $vars = array();
        $vars['msg'] = $e->getMessage();
        $vars['errFile'] =  $e->getFile();
        $vars['errLine'] = $e->getLine();
        $vars['trace'] = array_slice($e->getTrace(), 1);

        extract($vars);
        require SYSTEM . '/views/exception.php';
    }


    /** GracePHP错误处理handler
     * @param int $errorLevel 错误级别
     * @param string $errorMessage 错误信息
     * @param string $file 出错文件
     * @param string $line 出错文件行数
     */
    public static function errorHandler($errorLevel, $errorMessage, $file, $line)
    {
        // 是否报告错误
        $report = true;

        $vars = array();

        switch($errorLevel)
        {
            case E_NOTICE:
                $report = false;
                break;
            case E_WARNING:
                $errorLevel = 'Warning';
                break;
            case E_ERROR:
                $errorLevel = 'Error';
                break;
            default:
                $errorLevel = 'Unknown';
                break;
        }

        if($report)
        {
            if(Config::getItem('errorReport.type') == 'product' && Config::getItem('errorReport.logToFile'))
            {
                $msg = '';
                $msg .= 'Level: [' . $errorLevel . ']' . "\r\n";
                $msg .= 'Details: ' . $errorMessage . "\r\n";
                $msg .= 'Position: In ' . $file . ' Line ' . $line . "\r\n\r\n";

                $logFile = 'log/' . date('y-m-d') . '.log';

                file_put_contents(CURRENT_MODULE . $logFile, $msg, FILE_APPEND);
            }
            else if(Config::getItem('errorReport.type') == 'dev')
            {
                $vars['errLevel'] = $errorLevel;
                $vars['errMsg'] = $errorMessage;
                $vars['errFile'] = $file;
                $vars['errLine'] = $line;
                extract($vars);

                require SYSTEM . '/views/error.php';
                exit;
            }
        }
    }
}